package com.hd.trans.ui.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.hd.trans.R;
import com.hd.trans.network.ApiServiceManager;
import com.hd.trans.network.RxSchedulers;
import com.hd.trans.network.bean.trans.BaseResponse;
import com.hd.trans.network.bean.trans.TextTransNewReq;
import com.hd.trans.network.bean.trans.TextTransNewRes;
import com.hd.trans.network.bean.trans.TextTransReq;
import com.hd.trans.network.bean.trans.TextTransRes;
import com.hd.trans.ui.base.BaseActivity;
import com.hd.trans.ui.service.NetDisposableObserver3;
import com.hd.trans.utils.ToastUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class TextTransActivity extends BaseActivity {
    private EditText etContent;
    private TextView tvTransResult;
    private Button btnStartTrans;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_text_trans;
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        super.initViewsAndEvents(savedInstanceState);
        initView();
        setListener();
        //initData();
    }

    private void initView() {
        etContent = findViewById(R.id.et_content);
        tvTransResult = findViewById(R.id.tv_trans_result);
        btnStartTrans = findViewById(R.id.btn_start_trans);
    }

    private void setListener() {
        btnStartTrans.setOnClickListener(v -> {
            //开始翻译
            String originalText = etContent.getText().toString();
            if(!TextUtils.isEmpty(originalText.trim())){
                startTrans(originalText);
            }else {
                ToastUtils.showInfo("请先输入待翻译文本");
            }
        });
    }

    private void startTrans(String originalText) {
        TextTransNewReq req = new TextTransNewReq();
        req.setFromLang("zh");
        req.setToLang("en");
        req.setFromText(originalText);
        req.setFromProduct("demo");
        req.setWithDiff(true);
        ApiServiceManager.INSTANCE.getTransitionNewApi()
                .tansText(req)
                .compose(RxSchedulers.applySchedulers())
                .subscribe(new NetDisposableObserver3<>(new NetDisposableObserver3.NetCallBack<TextTransNewRes>() {
                    @Override
                    public void onResponse(TextTransNewRes response) {
                        if (response != null) {
                            tvTransResult.append(response.getToText());
                            tvTransResult.append("\n");
                        }
                    }

                    @Override
                    public void onError(int code, String msg) {
                        tvTransResult.append("\n");
                        tvTransResult.append("onError:-----------");
                        tvTransResult.append(msg);
                        tvTransResult.append("\n");
                    }

                    @Override
                    public void onTokenInvalid(String msg) {
                        tvTransResult.append("\n");
                        tvTransResult.append("onTokenInvalid:-----------");
                        tvTransResult.append(msg);
                        tvTransResult.append("\n");
                    }
                }));
    }

    private void startTransDiff(String originalText){
        TextTransReq req = new TextTransReq();
        req.setFromLang("zh");
        req.setToLang("en");
        req.setFromText(originalText);
        req.setFromProduct("demo");
        ApiServiceManager.INSTANCE.getTransitionNewApi()
                .tansTextDiff(req)
                .compose(RxSchedulers.applySchedulers())
                .subscribe(new NetDisposableObserver3<>(new NetDisposableObserver3.NetCallBack<BaseResponse<TextTransRes>>() {
                    @Override
                    public void onResponse(BaseResponse<TextTransRes> response) {
                        if (response != null) {
                            if(response.getData() instanceof TextTransRes){
                                tvTransResult.append(response.getData().getTgt_text());
                                tvTransResult.append("\n");
                            }else {

                            }
                        }
                    }

                    @Override
                    public void onError(int code, String msg) {
                        tvTransResult.append("\n");
                        tvTransResult.append("onError:-----------");
                        tvTransResult.append(msg);
                        tvTransResult.append("\n");
                    }

                    @Override
                    public void onTokenInvalid(String msg) {
                        tvTransResult.append("\n");
                        tvTransResult.append("onTokenInvalid:-----------");
                        tvTransResult.append(msg);
                        tvTransResult.append("\n");
                    }
                }));
    }


    public void runnable() throws Exception {
        //POST表单请求方式
        OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("fromLang", "zh")
                .addFormDataPart("toLang", "en")
                .addFormDataPart("fromText", "文本翻译")
                .addFormDataPart("fromPrduct", "demo")
                .build();
        Request request = new Request.Builder()
                .url("https://nnapi.nnxieli.com/trans_diff")
                .post(formBody)
                .build();

        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

        System.out.println(response.body().string());
        Log.i("liaoyucheng",response.body().string());
    }

    private String responseString() {//要在线程中执行该方法；用途判断是否支持接口功能
        HttpURLConnection connection = null;
        StringBuilder builder = new StringBuilder();
        InputStream in = null;
        InputStreamReader isr = null;
        BufferedReader reader = null;
        boolean success = false;
        try {
            //https://nnapi.nnxieli.com/trans_diff?fromLang=zh&toLang=en&fromText=bb&fromPrduct=demo
            URL url = new URL("https://nnapi.nnxieli.com/trans_diff");
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(1000);
            connection.setRequestMethod("OPTIONS");
            if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
                in = connection.getInputStream();
                isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                reader = new BufferedReader(isr);
                String line;
                while (null != (line = reader.readLine())) {
                    builder.append(line);
                }
                success = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != connection) {
                connection.disconnect();
            }

            try {
                if (null != in) {
                    in.close();
                }

                if (null != isr) {
                    isr.close();
                }

                if (null != reader) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (success) {
            return builder.toString();
        } else {
            return null;
        }
    }
}
